#!/bin/bash
#
# This script does quite a few things, some of which happen everytime it runs,
# and some of which only happen when /var/db/.DenisonSetupDone doesn't exist.
#
# THINGS THAT HAPPEN ON EVERY RUN:
#	1) Check to see if at least one network interface has a 140.141 address.
#		(if this fails, nothing else happens)
#	2) Sets the hostname by getting the MAC of en0 and asking registerip if
#	there is a hostname associated with it. If there isn't, the computer name
#	will contain the term "Unregistered" to indicate a registraion issue.
#

#
# Variables used all through the script
#
defaultHostName="Unregistered-Macintosh"
defaultBonjourName="Unregistered-Macintosh"


#
# FULL PATHS TO BINARIES
# (See below for other variable definitions.)
#
chown="/usr/sbin/chown"
chmod="/bin/chmod"
defaults="/usr/bin/defaults"
dscl="/usr/bin/dscl"
systemsetup="/usr/sbin/systemsetup"
FLAG_FILE="/var/db/.DenisonSetupDone"


if [ ! -e "${FLAG_FILE}" ]; then

	#
	# First we'll make sure that the network is available on any interface.
	# Specifically, we're looking for Denison's network.
	#
	x=0
	numIpAddresses=`/sbin/ifconfig | /usr/bin/grep 140.141 | /usr/bin/wc -l`
	while [[ $x -le 30 && $numIpAddresses -lt 1 ]]
	do
		echo "No 140.141.x.x ip address. Will check again in 5 seconds."
		/bin/sleep 5
		x=$(( $x + 1 ))
		numIpAddresses=`/sbin/ifconfig | /usr/bin/grep 140.141 | /usr/bin/wc -l`
	done
	
	if [ $numIpAddresses -lt 1 ]
	then
		echo "denison-setup will not run without a 140.141 address."
		exit 0
	fi



	#
	# Query registerip for the hostname of the computer and set it accordingly.
	# If registerip doesn't know about the computer, set the hostname to
	# "Unregistered MacCore 10-11"
	#
	mac=`ifconfig en0 | grep -e "\([0-9a-fA-F]\{2\}:\)\{5\}" | sed 's/^ *[^ ]* //'`
	ip=`ifconfig | grep 140.141 | sed 's/^[^0-9]*\(140.141.[0-9]*.[0-9]*\).*$/\1/'`

	host=`curl -s "https://registerip.denison.edu/services/hostbymac.php?mac=${mac}"`
	realHost=`echo -n "${host}" | sed 's/\([^\.]*\).*$/\1/'`

	if [ -n "${realHost}" ]
	then
		munkiIdentifier=`defaults read /Library/Preferences/ManagedInstalls ClientIdentifier`
		if [ -z `echo "${munkiIdentifier}" | grep "generic"` ]; then
			echo "It appears that the ClientIdentifier has already been updated."
			echo "Bailing out without making any changes"
		else
			m=`echo "${munkiIdentifier}" | sed 's/generic//'`
			newManifest="${m}${realHost}"
			defaults write /Library/Preferences/ManagedInstalls \
				ClientIdentifier "${newManifest}"
			
			bonjourname="${realHost}"
			hostname="${realHost}"
			
			# Have the system create the desired manifest if need be.
			/usr/bin/curl "http://apple-prime.cache.denison.edu/manifestManager.php?manifest=${newManifest}"
		fi
		touch "${FLAG_FILE}"
	else
		bonjourname="${defaultBonjourName}"
		hostname="${defaultHostName}"
	fi

	$systemsetup -setcomputername "${bonjourname}"
	$systemsetup -setlocalsubnetname "${bonjourname}"
	/usr/sbin/scutil --set HostName "${hostname}"
fi
